package com.roadrunner;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.AsyncTaskLoader;

public class MyHttp extends AsyncTaskLoader<String> {
	private Bundle bundle;
	private ProgressDialog dialog;
	private Context context;
	private String httpText;
	
	private int requestFunction = 0;
	
	public MyHttp(Context context, Bundle args)
	{
		super(context); 
		
		this.context = context;
		bundle = args;
		requestFunction = bundle.getInt("requestFunction");
		
		this.dialog = new ProgressDialog(context);
		this.dialog.setTitle("Loading");
		this.dialog.setMessage("the job list is loading");
		if (!this.dialog.isShowing()) {
			this.dialog.show();
		}
		
		httpText = "";
	}

	@Override
	protected void onStopLoading() {
		super.onStopLoading();
		
		this.dialog.dismiss();
	}

	@Override
	public String loadInBackground() {
		
		String url = bundle.getString("URL_CALL");
	    
		DefaultHttpClient client = new DefaultHttpClient();
		
		int job = bundle.getInt("requestFunction");
		switch(job)
		{
		case MainActivity.JOB_CHANGE_SRV:
		{
			HttpGet httpGet = new HttpGet(url);
		       
			try {			
				HttpResponse execute = client.execute(httpGet);
				InputStream content = execute.getEntity().getContent();
	
				BufferedReader buffer = new BufferedReader(new InputStreamReader(
						content));
				String s = "";
				while ((s = buffer.readLine()) != null) {
					httpText += s;
				}
	
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			String text = "newServer,"+httpText;
			httpText = text;
		}
		break;
		
		case MainActivity.JOB_SAVE_STATE:
			{
				 HttpPost httpPost = new HttpPost(url);
				 try {
					
					 	// Add your data
					 	String id = bundle.getString("orderId_editjobstate");
					 	String state = bundle.getString("jobState_edit");
					 	
				        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				        nameValuePairs.add(new BasicNameValuePair("orderId_editjobstate", id));
				        nameValuePairs.add(new BasicNameValuePair("jobState_edit", state));
				        if(state.equals("RESERVED"))
				        {
				        	String user = bundle.getString("transporter_name");
				        	nameValuePairs.add(new BasicNameValuePair("transporter_name", user));
				        }
				        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
						
				        HttpResponse execute = client.execute(httpPost);
						InputStream content = execute.getEntity().getContent();
			
						BufferedReader buffer = new BufferedReader(new InputStreamReader(
								content));
						String s = "";
						while ((s = buffer.readLine()) != null) {
							httpText += s;
						}
			
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			break;
			
		default:
			{			
				HttpGet httpGet = new HttpGet(url);
			       
				try {			
					HttpResponse execute = client.execute(httpGet);
					InputStream content = execute.getEntity().getContent();
		
					BufferedReader buffer = new BufferedReader(new InputStreamReader(
							content));
					String s = "";
					while ((s = buffer.readLine()) != null) {
						httpText += s;
					}
		
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		}
		
			

		this.dialog.dismiss();
		
		return httpText;
	}
	
	 @Override
	  public void deliverResult(String text) {
	    if (isReset()) {
	      // The Loader has been reset; ignore the result and invalidate the data.
	      releaseResources(text);
	      return;
	    }
	 
	    // Hold a reference to the old data so it doesn't get garbage collected.
	    // We must protect it until the new data has been delivered.
	    String oldtext = httpText;
	    httpText = text;
	 
	    if (isStarted()) {
	      // If the Loader is in a started state, deliver the results to the
	      // client. The superclass method does this for us.
	      super.deliverResult(text);
	    }
	 
	    // Invalidate the old data as we don't need it any more.
	    if (oldtext != null && oldtext != text) {
	      releaseResources(oldtext);
	    }
	  }
	 
	 @Override
	  protected void onStartLoading() {
	    if (httpText != null) {
	      // Deliver any previously loaded data immediately.
	      deliverResult(httpText);
	    }
	 
	    if (takeContentChanged() || httpText == null) {
	      forceLoad();
	    }
	  }
	 
	  @Override
	  protected void onReset() {
	    // Ensure the loader has been stopped.
	    onStopLoading();
	 
	    // At this point we can release the resources associated with 'mData'.
	    if (httpText != null) {
	      releaseResources(httpText);
	      httpText = null;
	    }
	 
	  }
	 
	  @Override
	  public void onCanceled(String data) {
	    // Attempt to cancel the current asynchronous load.
	    super.onCanceled(data);
	 
	    // The load has been canceled, so we should release the resources
	    // associated with 'data'.
	    releaseResources(data);
	  }

	private void releaseResources(String oldtext) {
		// TODO Auto-generated method stub
		
	}
}